<?php
include_once(SYSTEM.'/Identity.php');
include_once(ROOT.'/Config.php');

class Authencate
{
	public $IdentityObject;
	
	public function __construct()
	{
		//$this->IdentityObject = $this->CheckLogin();
	}
	
	public function Authorize($roles)
	{
		if($this->IdentityObject.IsAuthencated)
		{
			$connection = new Mongo(WebConfig::$ConnectionString['host']);
		    $connection->selectDB(WebConfig::$ConnectionString['MiGiDB']);
		}
	}

	public function SignIn($permanent, $userName)
	{
		$exp = 0;
		
		if($permanent)
		{
			$exp = $exp + 365*24*60*60;
		}
		else
		{
			$exp = $exp + 60*60;
		}
		
		$key = '123';
		$text = $userName . '/' . $key . '/' . $exp;
		$hash = $userName . $key;
		$cookie = $text . '|' . $hash;
		
		$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
		$encryptCookie = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $cookie, MCRYPT_MODE_ECB, $iv);
		
		setcookie('Apollo_AUTHX',$encryptCookie, time()+ $exp, '', '', false, true);
	}

	public function SignOut()
	{
		setcookie('Apollo_AUTHX','', time() - 3600);
	}
	
	public function CheckLogin(){
		
		$key = WebConfig::$AppSetting['Key'];
		if(!isset($_COOKIE['Apollo_AUTHX']))
		{
			$identityObject = new Identity('', false);
			return $identityObject;
		}
		$cookie = $_COOKIE['Apollo_AUTHX'];
		$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
		$decry = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cookie, MCRYPT_MODE_ECB,$iv);
	
		$text = explode('|',$decry);
		$data = explode('/', $text[0]);
		array_push($data, $text[1]);
		
		$arr = $data;
		
		$hash = $arr[0] . $arr[1];
		
		if(strcmp($hash, $arr[3]))
		{
			$identityObject = new Identity($arr[0], true);
			return $identityObject;
		}
		else
		{
			$identityObject = new Identity('', false);
			return $identityObject;
		}
	}
}
